package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtils {
    private static DataSource dataSource;
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    static {
        Properties properties = new Properties();
        try (InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("/druid.properties")) {
            properties.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static DataSource getDataSource() {
        return dataSource;
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public static Connection getConnection(boolean transactional) throws SQLException {
        if (transactional) {
            Connection connection = threadLocal.get();
            if (null == connection) {
                connection = getConnection();
                threadLocal.set(connection);
            }
            return connection;
        }
        return getConnection();
    }

    public static void releaseConnection() {
        threadLocal.set(null);
    }
}
